import axios from 'axios'
import {ElLoading} from 'element-plus'

let loadingInstance1 = null
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    config.headers.token = localStorage.getItem("token")
    loadingInstance1 = ElLoading.service({fullscreen: true})
    return config;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    const res = response.data
    res?.data?.token && localStorage.setItem("token", res?.data?.token);
    loadingInstance1 && loadingInstance1.close()
    return response;
}, function (error) {
    loadingInstance1 && loadingInstance1.close()
    const {status} = error.response
    if (status === 401) {
        localStorage.removeItem("token")
        window.location.href = "#/login"
    }
    return Promise.reject(error);
});
